var driver_list = "";
var driver_unavailable_array = [];
var driver_unavailable_array_types = [];

function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json){
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name + '</a> ' +
                      'Phone: (' + json.tmpo_poc_phone.substr(0,3) + ') ' +
                      json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    ); 
}

function setRowColors() {
    $("#duLog tbody").removeClass('tableAlternateColor');
    $("#duLog tbody:odd").addClass('tableAlternateColor');
}

function getDriverUnavailable() {
	$.getJSON(
        '/api/tmpo/du_type/',
        function(json) {
            driver_unavailable_array_types = jQuery.makeArray(json.types);  
        }
    );
    var today_boolean = new Date();
    today_boolean.setDate(today_boolean.getDate()-14);    
    $.ajax({
        type: "GET",
        url: '/api/tmpo/du/driver/' + $.qs('id') + '/',
        dataType: "json",
        success: function(json) {
            driver_unavailable_array = jQuery.makeArray(json.events);
            jQuery.map(json.events,function(n){
                var formatted_du_date = new Date();
                formatted_du_date.setDate($.y4m2d2_to_d2m3y4(
                    n.start.replace(/:|-| /g, " ").substr(0,10)).substr(0,2));
                formatted_du_date.setMonth(dateCheck($.y4m2d2_to_d2m3y4(
                    n.start.replace(/:|-| /g, " ").substr(0,10)).substr(3,3)));
                formatted_du_date.setFullYear($.y4m2d2_to_d2m3y4(
                    n.start.replace(/:|-| /g, " ").substr(0,10)).substr(7,4));
                if (formatted_du_date >= today_boolean) {
                $("#duLog").append("<tbody class='tableAlternateColor' "+
                "id='tbody_"+n.id+"'><tr><td><span id='span_edit_" + n.id+ 
                "' class='hoverButton'>Edit</span>"+n.description+"</td><td>"+
                displayDate(n.start.replace(/:|-| /g, " ").substr(0,10))+
                "</td><td>"+n.start.replace(/:|-| /g, "").substr(8,4)+
                "</td><td>"+n.end.replace(/:|-| /g, "").substr(8,4)+
                "</td><td>"+n.comments+"</td></tr></tbody> ");
                }
            });
        },
        complete: function(json){
            setRowColors();
            bindDriverDuRows();
            $("#addEntry").click(function() {
                addEntry();
                return false;
            });
            console.debug('complete');
        },
        error: function(json){
            console.debug('fail');
        }
    });
}

function getDrivers() {
    $.ajax({
        type: "GET",
        url: ($.qs('id')) ? '/api/tmpo/drivers/'+$.qs('id')+
            '/' : '/api/tmpo/drivers/',
        dataType: "json",
        success: function(json) {
            driver_list = $(json.drivers);
            jQuery.map(json.drivers,function(n){       
                $("#driverLog").append("<tbody class='tableAlternateColor' "+
                "id='driverTable'><tr><td><span id='span_driver' "+
                "class='hoverButton'>Edit</span>"+n.name+"</td><td>"+
                n.telephone+"</td><td>"+n.address+"</td><td>"+n.license_number+
                "</td><td>"+displayDate(
                n.license_expiration.replace(/:|-| /g, " ").substr(0,10))+
                "</td><td>"+n.license_class+"</td><td>"+n.license_endorsements+
                "</td><td>"+n.license_restrictions+"</td></tr></tbody> ");
            });
        },
        complete: function(json){
            bindDriverRows();
            console.debug('complete');
        },
        error: function(json){
            console.debug('fail');
        }
    });
}

function toggleButtons(x) {
    (x) ? $("#addEntry").addClass('buttonInactive') : $("#add"+
          "Entry").removeClass('buttonInactive');
}

function resetDriverTable() {
    toggleButtons(false);
    driver_list = "";
    $("#driver_edit_row").remove();
	$("#driverTable").remove();
	getDrivers();  
}

function resetDuTable() {
    toggleButtons(false);
    driver_unavailable_array = {};
    $("#duLog tbody").remove();
    getDriverUnavailable();   
}

function bindDriverRows() {
    jQuery.map(driver_list, function(row){
        if( $("#driverTable:has[class!='highlight']").length ){
            $("#driverTable").hover(
                function () { 
                    $("#driverTable").addClass('highlight'); 
                },
                function () { 
                    $("#driverTable").removeClass('highlight'); 
                }
            );
            $("#span_driver").unbind();
            $("#span_driver").click(
                function () { 
                    editDriver(row);
                    return false;
                }
            );
            $("#driverTable").click(
                function () { 
                    editDriver(row);
                    return false; 
                }
            );
            $("#driverTable tr td span").parent().unbind();
        }
    });
    $("#cancel_driver_detail").click(function() {
        resetDriverTable();
        return false;
    });
}

function bindDriverDuRows() {
    jQuery.map(driver_unavailable_array, function(row){
        if( $("#tbody_" + row.id + ":has[class!='highlight']").length ){
            $("#tbody_" + row.id).unbind();
            $("#tbody_" + row.id).hover(
                function () { 
                    $("#tbody_" + row.id).addClass('highlight'); 
                },
                function () { 
                    $("#tbody_" + row.id).removeClass('highlight'); 
                }
            );        
            $("#span_edit_" + row.id).unbind();
            $("#tbody_" + row.id).click(              
                function () {
                    editEntry(row); 
                }
            );
            $("#span_edit_" + row.id).click(              
                function () {
                    editEntry(row); 
                }
            );
            $("#tbody_" + row.id + " tr td span").parent().unbind();
        } 
    });    
}

function editDriver(row) {
    resetDuTable();
    $("#driverLog tbody").unbind();
    $("#driverTable").replaceWith(
        "<tbody class='tableActiveColor' id='driver_edit_row'>"+
        "<tr><td><input name='name' type='text' size='12' id='name'"+
        " value='"+row.name+"' /></td><td><input id='phone_area' "+
        "type='text' maxlength='3' size='3' name='phone_area' value='"+
        row.telephone.substr(0,3)+"' />-<input id='phone_prefix' "+
        "type='text' maxlength='3' size='3' name='phone_prefix' value='"+
        row.telephone.substr(4,3)+"'/>-<input id='phone_suffix' type='text'"+
        " maxlength='4' size='4' name='phone_suffix' value='"+
        row.telephone.substr(8,4)+"'/></td><td><input name='address' "+
        "type='text' size='12' id='address' value='"+row.address+
        "' /></td><td><input name='license_number' type='text' size='9'"+
        " id='license_number' value='"+row.license_number+"' /></td><td>"+
        "<input name='license_expiration' type='text' size='9' "+
        "id='license_expiration' value='"+displayDate(
        row.license_expiration.replace(/:|-| /g, " ").substr(0,10))+
        "' /><h6 id='exp_date'>DD MM YYYY</h6></td><td>"+
        "<input name='license_class' type='text' size='2' "+
        "id='license_class' value='"+row.license_class+"' />"+
        "</td><td><input name='license_endorsements' type='text'"+
        " size='9' id='license_endorsements' value='"+row.license_endorsements+
        "' /></td><td><input name='license_restrictions' type='text' size='9'"+
        " id='license_restrictions' value='"+row.license_restrictions+
        "' /></td></tr><tr><td colspan='9'><a class='button' href='#'"+
        " id='edit_driver' ><img src='/tmpo/images/icons/save.gif' "+
        "alt='' />Save</a><a class='button' href='#'id='cancel_driver_detail'>"+
        "<img src='/tmpo/images/icons/close.gif' alt='' />Cancel</a>"+
        "</td></tr></tbody>");
    $("#cancel_driver_detail").click(function() {
        resetDriverTable();
        return false;        
    });
    $("#edit_driver").click(function() {
        if( validateRequestFormDriver("cancel_driver_detail") ){
            editRequestDriver(row.id);
        }
        return false;
    });
}

function validateRequestFormDriver(last_btn){
    var date_error_message = "Please enter a complete date."+
        "<br>Example: 01 JAN 2000";
    var error_count = 0;
    $("#message").remove();
    $("td[class='tableErrorColor']").removeClass("tableErrorColor");
    $("span[class='errorMessage']").remove();
    $("input[class='formError']").removeClass('formError');
    $("td br").remove();
    if( !$.is_d2m3y4($("#license_expiration").val())) {
        error_count++;
        $("#license_expiration").parent().append(
            '<br/><span class="errorMessage">'+date_error_message+'</span>');
        $("#license_expiration").parent().addClass("tableErrorColor");
        $("#license_expiration").addClass("formError");
    }
    var required_form_data = "Please complete required field.";
    var required_field_list = ['name','phone_area','phone_prefix',
        'phone_suffix','address','license_number','license_expiration',
        'license_class','license_endorsements','license_restrictions'];
    jQuery.map(required_field_list, function(field) { 
        if( !$("#"+field).val()) {
            error_count++;
            $("#"+field).parent().append(
                '<br><span class="errorMessage">'+
                required_form_data+'</span>');
            $("#"+field).parent().addClass("tableErrorColor");
            $("#"+field).addClass("formError");
        }
    });
    var phone_error_message = "Please enter a 10-digit telephone number. "+
        "Example: 123-456-7890";    
    var reqPhoneList = ['phone_area','phone_prefix'];
    var reqPhoneListSuffix = ['phone_suffix'];
    jQuery.map(reqPhoneList, function(field) {
        if((!$("#"+field).val())) {
            error_count++;
            $("#"+field).parent().append(
                '<br><span class="errorMessage">'+phone_error_message+
                '</span>');
            $("#"+field).parent().addClass("tableErrorColor");
            $("#"+field).addClass("formError");
        } else {
            var temp = $("#"+field).val();
            if (!validPhoneThree(temp)) {
                error_count++;
                $("#"+field).parent().append(
                    '<br><span class="errorMessage">'+phone_error_message+
                    '</span>');
                $("#"+field).parent().addClass("tableErrorColor");
                $("#"+field).addClass("formError");
            }
        }
    });
    jQuery.map(reqPhoneListSuffix, function(field) { 
        if((!$("#"+field).val())) {
            error_count++;
            $("#"+field).parent().append(
                '<br><span class="errorMessage">'+phone_error_message+
                '</span>');
            $("#"+field).parent().addClass("tableErrorColor");
            $("#"+field).addClass("formError");
        } else {
            var temp = $("#"+field).val();
            if (!validPhoneFour(temp)) {
                error_count++;
                $("#"+field).parent().append(
                    '<br><span class="errorMessage">'+phone_error_message+
                    '</span>');
                $("#"+field).parent().addClass("tableErrorColor");
                $("#"+field).addClass("formError");
            }
        }
    });
    if(error_count){    
        $("#"+last_btn).after(
            '<span class="generalErrorMessage" '+
            'name="message" id="message"><img alt="" '+
            'src="/tmpo/images/icons/alert.gif"/>Please'+
            ' correct errors above to save form.</span>');
    } else {
        $("#message").remove();
        $("#"+last_btn).after(
            '<span id="message" name="message" class="waitMessage">'+
            '<img src="/tmpo/images/icons/hourglass.gif" alt="" />'+
            'Your changes are being saved. Please wait.</span>');
        return true;
    }
}

function editRequestDriver(id) {
    var form_data_update_driver = {	
        name: $("#name").val(),
        position: $("#position").val(),
        telephone: $("#phone_area").val()+'-'+$("#phone_prefix").val()+'-'+
                   $("#phone_suffix").val(),
        address: $("#address").val(),
        license_number: $("#license_number").val(),
        license_expiration: $.d2m3y4_to_y4m2d2(
                            $("#license_expiration").val()) + ' 01:00',
        license_class: $("#license_class").val(),
        license_endorsements: $("#license_endorsements").val(),
        license_restrictions: $("#license_restrictions").val()
    };
    $.ajax({
        url: '/api/tmpo/drivers/'+id+'/',
        type: "POST",
        data: form_data_update_driver,
        success: function() {
            console.debug("success");
        },
        complete: function() {
            resetDriverTable();
            console.debug("complete");
        },
        error: function(){
            console.debug("fail");
        }
    });    
}

function addEntry() {
    toggleButtons(true);
    $("#tbody_add").remove();
    $("#duLog").prepend(
        "<tbody class='tableActiveColor' id='tbody_add'>"+
        "<tr><td><label><select id='du_type' ></select></label></td>"+
        "<td><input name='start'"+"type='text' id='start'"+
        " size='15' /><br><h6 id='start_h'>DD MMM YYYY</h6>"+
        "</td><td><input name='start_time' type='text' "+
        "id='start_time'size='9' />"+"<br><h6 id='start_time_h'>0000</h6>"+
        "</td><td><input name='finish_time' "+"type='text' "+
        "id='finish_time' size='9' /><br><h6 id='finish_time_h'>0000"+
        "</h6></td><td><textarea name='comments'  id='comments' cols='33' >"+
        "</textarea></td></tr><tr><td colspan='6'><a class='button' href='#' "+
        "id='add_new_entry'> <img src='/tmpo/images/icons/save.gif' alt='' />"+
        "Save</a><a class='button' href='#' id='cancel_du'> "+
        "<img src='/tmpo/images/icons/close.gif' alt='' />Cancel</a>"+
        "</td></tr></tr></tbody>");
    jQuery.each(driver_unavailable_array_types, function(i,n) { 
        $("#du_type").append('<option value="'+n.id+'">'+
            n.description+'</option>');
    });
    edit_boolean = false;
    $("#add_new_entry").click(function() {
        if( validateDuForm("cancel_du", false) ){  
            addRequest();
        }
        return false;
    });
    $("#cancel_du").click(function(){
        resetDuTable();
        toggleButtons(false);
        return false;
    });
    bindAutoDate("[name=start]")
    bindAutoTime("[name=start_time]")
    bindAutoTime("[name=finish_time]")


}


function validateDuForm(last_btn, edit_boolean){
    var date_error_message = "Please enter a complete date. "+
        "Example: 01 JAN 2000";
    var time_error_message = "Please use four-digit military time. "+
        "Example: 1430";
    var error_count = 0;
    $("#message").remove();
    $("td[class='tableErrorColor']").removeClass("tableErrorColor");
    $("span[class='generalErrorMessage']").remove();
    $("span[class='errorMessage']").remove();
    $("input[class='formError']").removeClass('formError');
    $("td br").remove();
    if( !$.is_d2m3y4($("#start").val())) {
        error_count++;
        $("#start_h").after('<span class="errorMessage">'+date_error_message+
            '</span><br>');
        $("#start").parent().addClass("tableErrorColor");
        $("#start").addClass("formError");        
    }
    var doop_entry = jQuery.grep(driver_unavailable_array, function(n, i){
        return (n.start.substr(0,10) == $.d2m3y4_to_y4m2d2($("#start").val()));
	});
	if(doop_entry.length > 0 && !(edit_boolean) ) {
        error_count++;
        $("#start_h").after('<span class="errorMessage">Event is already '+
            'scheduled for this day.</span><br>');
        $("#start").parent().addClass("tableErrorColor");
        $("#start").addClass("formError");        
    }
    if( !$.is_24hour($("#start_time").val())) {
        error_count++;
        $("#start_time_h").after('<span class="errorMessage">'+
            time_error_message+'</span><br>');
        $("#start_time").parent().addClass("tableErrorColor");
        $("#start_time").addClass("formError");
    }else {
        var start = $("#start_time").val();
    }           
    if( !$.is_24hour($("#finish_time").val())) {
        error_count++;
        $("#finish_time_h").after('<span class="errorMessage">'+
            time_error_message+'</span><br>');
        $("#finish_time").parent().addClass("tableErrorColor");
        $("#finish_time").addClass("formError");
    }else {
        var finish = $("#finish_time").val();
    }	
    if ( start >= finish ){
        error_count++;
        error = "Start time must precede finish time.";
        $("#start_time_h").after('<span class="errorMessage">'+
            error+'</span><br>');
        $("#start_time").parent().addClass("tableErrorColor");
        $("#start_time").addClass("formError");
        $("#finish_time_h").after('<span class="errorMessage">'+
            error+'</span><br>');
        $("#finish_time").parent().addClass("tableErrorColor");
        $("#finish_time").addClass("formError");
    }
    var required_form_data = "Please complete required field.";
    var required_field_list = [];    
    jQuery.map(required_field_list, function(field) { 
    if( !$("#"+field).val()) {
        error_count++;
        $("#"+field + "").after('<span class="errorMessage">'+
            required_form_data+'</span>');
        $("#"+field).parent().addClass("tableErrorColor");
        $("#"+field).addClass("formError");
        }
    });
    if(error_count){    
    $("#"+last_btn).after('<span class="generalErrorMessage" name="message"'+
        ' id="message"><img alt="" src="/tmpo/images/icons/alert.gif"/>'+
        'Please correct errors above to save form.</span>');
    }else {
        $("#message").remove();
        $("#"+last_btn).after(
            '<span id="message" name="message" class="waitMessage">'+
            '<img src="/tmpo/images/icons/hourglass.gif" alt="" />'+
            'Your changes are being saved. Please wait.</span>');
        return true;
    }
}

function addRequest() {
    var form_description = jQuery.grep(driver_unavailable_array_types, 
        function(n) {return (n.id ==  $("#du_type").val());});
    var form_data_add_unavailability = {
        event_type: $("#du_type").val(),
        finish: $.d2m3y4_to_y4m2d2($("#start").val()) + ' ' + 
            $("#finish_time").val().substr(0,2) + ':' + 
            $("#finish_time").val().substr(2,2),
        start: $.d2m3y4_to_y4m2d2($("#start").val()) + ' ' + 
            $("#start_time").val().substr(0,2) + ':' + 
            $("#start_time").val().substr(2,2),
        comments: $("#comments").val(),
        description: form_description[0].description,
        driver_id: $.qs('id')
    };
    $.ajax({
        url: '/api/tmpo/du/',
        type: "PUT",
        data: form_data_add_unavailability,
        success: function() {
            console.debug("success");            
        },
        complete: function() {
            toggleButtons(false);
            resetDuTable();            
            console.debug("complete");
        },
        error: function(){
            console.debug("fail");
        }
    });   
}

function editEntry(row) {
    toggleButtons(true);
    $("#tbody_add").remove();
    $("#duLog tbody").unbind();
    $("#tbody_" + row.id).replaceWith("<tbody class='tableActiveColor' "+
        "id='tbody_edit'><tr><td><label><select name='du_type' id='du_type'>"+
        "</select ></label></td><td><input name='start' type='text' "+
        "id='start' size='15' value='"+
        $.y4m2d2_to_d2m3y4(row.start.replace(/:|-| /g," ").substr(0,10))+"'/>"+
        "<h6 id='start_h'>DD MMM YYYY</h6></td><td><input name='start_time' "+
        "type='text' id='start_time' size='9' value='"+
        row.start.replace(/:|-| /g, "").substr(8,4)+"' />"+
        "<h6 id='start_time_h'>0000</h6></td><td><input name='finish_time'"+ 
        "type='text' id='finish_time' size='9' value='"+
        row.end.replace(/:|-| /g, "").substr(8,4)+"' />"+
        "<h6 id='finish_time_h'>0000</h6></td><td><textarea name='comments' "+
        "id='comments' cols='33' >"+row.comments+"</textarea></td></tr><tr>"+
        "<td colspan='9'><a class='button' href='#'id='edit_entry' >"+
        "<img src='/tmpo/images/icons/save.gif' alt='' />Save</a>"+
        "<a class='button' href='#'id='cancel_du'>"+
        "<img src='/tmpo/images/icons/close.gif' alt=''  />Cancel</a>"+
        "<a class='button' href='#'id='delete'>"+
        "<img src='/tmpo/images/icons/delete.gif' alt=''  />"+
        "Delete</a></td></tr></tbody>");
    jQuery.each(driver_unavailable_array_types, function(i,n) { 
        $("#du_type").append('<option value="'+n.id+'">'+
            n.description+'</option>');
    });
    $("#du_type option[value='"+row.type+"']").attr("selected","selected");
    $("#cancel_du").click(function () { 
        toggleButtons(false);
        resetDuTable();
        return false;
    });
    $("#edit_entry").click(function(){
        if(validateDuForm("delete",true)){ 
            toggleButtons(false);
            editRequest(row.id);
        }
        return false;
    });
    $("#delete").click(function() { 
        toggleButtons(false);
        deleteRequest(row);
        return false;
    });
}

function editRequest(id) {
    var form_description = jQuery.grep(driver_unavailable_array_types, 
        function(n) {return (n.id ==  $("#du_type").val());});
    var form_data_update_unavailability = {
        type: $("#du_type").val(),
        finish: $.d2m3y4_to_y4m2d2($("#start").val())+' '+
            $("#finish_time").val().substr(0,2)+':'+
            $("#finish_time").val().substr(2,2),
        start: $.d2m3y4_to_y4m2d2($("#start").val())+' '+
            $("#start_time").val().substr(0,2)+':'+
            $("#start_time").val().substr(2,2),
        comments: $("#comments").val(),
        description: form_description[0].description,
        driver_id: $.qs('id')
    };
    $.ajax({
        url: '/api/tmpo/du/'+id+'/',
        type: "POST",
        data: form_data_update_unavailability,
        success: function() {
            console.debug("success");
        },
        complete: function() {
            toggleButtons(false);
            resetDuTable();
            console.debug("complete");
        },
        error: function(){
            console.debug("fail");
        }
    });    
}

function deleteRequest(row) {
    var deleteCommitment = function(){
        $.ajax({
            type: "DELETE",
            url: '/api/tmpo/du/'+row.id+'/',
            dataType: "text",
            success: function(){
                toggleButtons(false);
                resetDuTable();
                console.debug("success");
            },
            complete: function(){
                console.debug("complete");
            },
            error: function(){
                console.debug("fail");
            }
        });
        clearTimeout(timeout_index);
        delete timeout_index;
    };
    timeout_index = setTimeout(deleteCommitment, 10000);
    $(window).unload( function (){
        if( typeof(timeout_index) != 'undefined' ){ 
            deleteCommitment();
        }
    });
    bindDriverDuRows();
    $("#tbody_edit tr").remove();
    $("#tbody_edit").append(
        '<tr><td colspan="10"><b>This entry has been deleted. '+
        '<span id="close_delete_' + row.id + '" class="inferLink">'+
        '<u>Close</u></span> | <span id="undo_delete_' + row.id + 
        '" class="inferLink"><u>Undo</u></span></b></td></tr>');
    $("#close_delete_" + row.id).click(function () {
        deleteCommitment();
        return false;
    });
    $("#undo_delete_" + row.id).click(function () {
        clearTimeout(timeout_index); 
        delete timeout_index;
        resetDuTable();
        return false;
    });
}

function bindAutoDate(selector) {
    $(selector).blur(function (e) {
        var v = $(selector).val()
        var sv = v.split(/\W+/).filter(function (f) { return (!!f) })
        if (sv[0]) {
            if (sv[0].length==1) {sv[0]="0"+sv[0]}
        }
        if (!sv[2]) {
            sv[2] = "" + new Date().getFullYear();
        }
        $(selector).val(sv.join(" "))
    })
}


function bindAutoTime(selector) {
    $(selector).blur(function (e) {
        var v = $(selector).val()
        if (v.length==3) { $(selector).val("0" + v)}
    })
}


$(function() {
    Functional.install();
    getSiteCfg();
    getDrivers();
    getDriverUnavailable();	    
});




